import { dom } from "../tool";

export interface SelectDataType {
    key: string | number;
    title: string | number;
    disabled?: boolean;
}
interface PropType {
    type?: 'select' | 'radio' | 'checkbox';
    data: SelectDataType[];
    value?: string | number | null | string[] | number[];
    onChange?: (value: string | number | null | undefined | string[] | number[]) => void;
    placeholder?: string;
    label?: string | HTMLElement;
    target?: HTMLElement;
}
interface SelectType {
    new(props?: PropType): SelectType;
    setData: (data: SelectDataType[]) => void;
    value?: string | number | null | string[] | number[];
    setValue: (value?: string | number | null | string[] | number[]) => void;
    render: (node?: HTMLElement) => HTMLElement;
    onChange?: (value: string | number | null | undefined | string[] | number[]) => void;
}

function Select(this: SelectType, props: PropType) {
    const { type = "select", data, value, onChange, placeholder = "请选择", label, target } = props;
    this.onChange = onChange;
    let container: any;
    let handleNode: any;
    const change = (event: any) => {
        this.value = event.target.value;
        if (this.onChange instanceof Function) {
            this.onChange(this.value);
        }
    }
    let options: any[] = [];
    if ('radio' === type) {

    } else if ('checkbox' === type) {

    } else {
        options = data.map((item: SelectDataType) => {
            const n: any = dom('option', {
                // innerText: item.title,
                child: dom('div', { innerText: item.title }),
                attribute: { value: item.key }
            });
            n.disabled = item.disabled;
            return n;
        });
        handleNode = dom('select', { target, className: "gkh-select", attribute: { placeholder }, childs: options })
        handleNode.onchange = change;
        if (label) {
            if (label instanceof Node) {
                container = dom('div', { target, className: 'gkh-form-item', childs: [dom('label', { child: label }), handleNode] })
            } else {
                container = dom('div', { target, className: 'gkh-form-item', childs: [dom('label', { innerText: label }), handleNode] })
            }
        } else {
            container = handleNode;
        }
    }
    this.setValue = (arg) => {
        this.value = arg;
        if (type == "select") {
            options.forEach((item: any) => {
                item.selected = item.value == arg
            })
        }
    }
    this.setValue(value);
    this.render = (node) => {
        if (node) {
            node.appendChild(container);
        }
        return container;
    }

    return this;
}

export default Select as unknown as SelectType;